package cn.yangliu.task.config;

import cn.yangliu.task.TaskFactoryBean;
import cn.yangliu.task.dao.TaskDao;
import cn.yangliu.task.service.TaskService;
import cn.yangliu.task.service.impl.TaskServiceImpl;
import cn.yangliu.task.socket.TaskSockectServer;
import cn.yangliu.task.socket.TaskSocketClient;
import cn.yangliu.task.utils.AppUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

import javax.annotation.Resource;

@Configuration
@EnableScheduling
@EnableConfigurationProperties(value = TaskProperties.class)
@ConditionalOnProperty(prefix = "spring.task", value = "enable", matchIfMissing = true)
public class TaskConfig {

    @Resource
    private TaskProperties properties;

    @Bean
    public AppUtils appUtils(){
        return new AppUtils();
    }

    @Bean
    @DependsOn("appUtils")
    @ConditionalOnMissingBean(ThreadPoolTaskScheduler.class)
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        return new ThreadPoolTaskScheduler();
    }

    @Bean
    @DependsOn({"appUtils","threadPoolTaskScheduler"})
    public TaskFactoryBean taskFactoryBean(){
        return  new TaskFactoryBean();
    }

    @Bean
    @ConditionalOnMissingBean(TaskService.class)
    public TaskService taskService(){
        return new TaskServiceImpl();
    }

    @Bean
    @ConditionalOnMissingBean(TaskDao.class)
    public TaskDao taskDao(){
        TaskDao taskDao = new TaskDao();
        taskDao.setTableName(properties.getTableName());
        return taskDao;
    }

    @Bean
    @ConditionalOnMissingBean(TaskSockectServer.class)
    public TaskSockectServer taskSockectServer(){
        TaskSockectServer server = new TaskSockectServer();
        server.setPort(properties.getPort());
        server.setEnableSocket(properties.getEnableSocket());
        return server;
    }

    @Bean
    @ConditionalOnMissingBean(TaskSocketClient.class)
    public TaskSocketClient taskSocketClient(){
        TaskSocketClient client = new TaskSocketClient();
        client.setPort(properties.getPort());
        client.setHost(properties.getHost());
        return client;
    }
}
